package com.langyiquan.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.langyiquan.config.AliSmsResource;
import com.langyiquan.enums.SmsPlatform;
import com.langyiquan.enums.YesOrNo;
import com.langyiquan.mapper.SmsLogMapper;
import com.langyiquan.pojo.SmsLog;
import com.langyiquan.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AliSmsServiceImpl implements SmsService {

    @Autowired
    private AliSmsResource aliSmsResource;

    @Autowired
    private SmsLogMapper smsLogMapper;

    @Override
    public void sendSms(String mobile) {

        String code = Math.random() * 9000 + 1000 + "";
        String templateCode = "SMS_176375033";

        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", aliSmsResource.getAccessKeyId(), aliSmsResource.getAccessKeySecret());
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", aliSmsResource.getProduct(), aliSmsResource.getDomain());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(mobile);
        request.setSignName(aliSmsResource.getSign());
        request.setTemplateCode(templateCode);
        request.setTemplateParam("{\"code\":" + code + "}");

        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
            String resultCode = sendSmsResponse.getCode();
            if("OK".equals(resultCode)){
                _addSmsLog(mobile,templateCode+"||"+"{\"code\":" + code + "}",YesOrNo.YES.type,"");
            }else{
                _addSmsLog(mobile,templateCode+"||"+"{\"code\":" + code + "}", YesOrNo.NO.type, sendSmsResponse.getMessage());
            }
        } catch (ClientException e) {
            _addSmsLog(mobile,templateCode+"||"+"{\"code\":" + code + "}", YesOrNo.NO.type, e.getMessage());
            e.printStackTrace();
        }

    }



    private void _addSmsLog(String mobile, String content, Integer result,String errSms){
        SmsLog smsLog = new SmsLog();
        smsLog.setMobile(mobile);
        smsLog.setContent(content);
        smsLog.setResult(result);
        smsLog.setErrMsg(errSms);
        smsLog.setResource(SmsPlatform.ALISMS.type);
        smsLogMapper.insert(smsLog);
    }

}
